import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useUserAuth, useAdminAuth } from '../hooks/useAuth';
import { Spin } from 'antd';

export const PrivateRoute = ({ children }) => {
  const location = useLocation();
  const isAdminRoute = location.pathname.startsWith('/admin');
  
  // 根据路由类型选择对应的认证hook
  // const authHook = isAdminRoute ? useAdminAuth() : useAuth();
  // 同时调用两个 Hook，避免条件调用
  const adminAuth = useAdminAuth();
  const userAuth = useUserAuth();
  const authHook = isAdminRoute ? adminAuth : userAuth;

  const { isAuthenticated, loading, user } = authHook;
  
  console.log('PrivateRoute 检查:', {
    isAuthenticated,
    loading,
    hasUser: !!user,
    userInfo: user ? { username: user.username, roles: user.roles } : null
  });
  
  // 如果还在加载中，显示加载状态
  if (loading) {
    console.log('PrivateRoute: 正在加载...');
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        height: '100vh' 
      }}>
        <Spin size="large" tip="加载中..." />
      </div>
    );
  }
  
  // 如果未认证，重定向到对应的登录页
  if (!isAuthenticated) {
    console.log('PrivateRoute: 用户未认证，重定向到登录页');
    const loginPath = isAdminRoute ? '/admin/login' : '/app/login';
    return <Navigate to={loginPath} replace />;
  }
  
  console.log('PrivateRoute: 用户已认证，允许访问');
  return children;
};